<template>
  <div class="article-list">
    <h3 class="article-list-title">用户列表</h3>
    <div class="article-list-wrap">
      <el-table :data="tableData" style="width: 100%" border>
        <el-table-column label="序号" width="80" align="center">
          <template slot-scope="scope">
            <span>{{ scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="ID" prop="id" width="100" align="center"></el-table-column>
        <el-table-column label="账号" prop="account"></el-table-column>
        <el-table-column label="用户名" prop="username"></el-table-column>
        <el-table-column label="性别" width="80" prop="gender" align="center"></el-table-column>
        <el-table-column label="注册时间" width="200">
          <template slot-scope="scope">
            <div class="date-time">{{ formatDateTime(scope.row.createAt) }}</div>
          </template>
        </el-table-column>
        <el-table-column align="right" width="280">
          <template slot="header">
            <el-input v-model="search" size="mini" placeholder="输入关键字搜索" clearable @clear="handleSearch"
              @keyup.enter.native="handleSearch"></el-input>
          </template>
          <template slot-scope="scope">
            <!-- 如果只有一个管理员且当前行是管理员，则不显示任何操作按钮 -->
            <template v-if="!(adminCount === 1 && scope.row.role == '1')">
              <el-button v-if="scope.row.role != '1' && scope.row.role != '-1' && scope.row.role != '-2'" size="mini"
                type="warning" @click="handleMute(scope.$index, scope.row)">
                禁言
              </el-button>
              <el-button v-if="scope.row.role != '1' && scope.row.role != '-1' && scope.row.role != '-2'" size="mini"
                type="danger" @click="handleBan(scope.$index, scope.row)">
                封禁
              </el-button>
              <el-button v-if="scope.row.role == '-1'" size="mini" type="success"
                @click="handleUnmute(scope.$index, scope.row)">
                解禁
              </el-button>
              <el-button v-if="scope.row.role == '-2'" size="mini" type="success"
                @click="handleUnban(scope.$index, scope.row)">
                解封
              </el-button>
              <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
            </template>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="article-list-footer">
      <el-pagination @current-change="currentChangeFn" background layout="prev, pager, next" :page-size="page_size"
        :pager-count="7" :total="total">
      </el-pagination>
    </div>
  </div>
</template>

<script>
import { itemsUser, deleteUser, muteUser, banUser, unmuteUser, unbanUser } from "../api/index"
import { requireLogin } from "../utils/auth"

export default {
  data() {
    return {
      tableData: [],
      search: '',
      page_num: 1,
      page_size: 5,
      total: 0,
      adminCount: 0
    }
  },
  methods: {
    formatDateTime(dateTimeStr) {
      if (!dateTimeStr) return ''
      const date = new Date(dateTimeStr)
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hours = String(date.getHours()).padStart(2, '0')
      const minutes = String(date.getMinutes()).padStart(2, '0')
      const seconds = String(date.getSeconds()).padStart(2, '0')
      return `${year}-${month}-${day}\n${hours}:${minutes}:${seconds}`
    },
    async deleteUserFn(id) {
      const isLoggedIn = await requireLogin()
      if (!isLoggedIn) {
        const result = await this.$showLoginPrompt()
        if (result.isConfirmed) {
          this.$router.push({ path: "/login" })
        }
        return
      }

      let token = localStorage.getItem("AUTO_TOKEN")
      await deleteUser({ token, id })
        .then(resData => {
          if (resData.code == 200) {
            this.$showSuccess('成功', resData.msg || '删除成功')
            this.itemsUserFn()
          } else {
            this.$showError('失败', resData.msg || '删除失败')
          }
        })
        .catch(() => {
          this.$showError('失败', '删除失败，请重试')
        })
    },
    async itemsUserFn() {
      const isLoggedIn = await requireLogin()
      if (!isLoggedIn) {
        const result = await this.$showLoginPrompt()
        if (result.isConfirmed) {
          this.$router.push({ path: "/login" })
        }
        return
      }

      let page_num = this.page_num
      let page_size = this.page_size
      await itemsUser({ page_num, page_size })
        .then(resData => {
          if (resData.code == 200) {
            this.tableData = resData.data || resData.result || []
            this.total = resData.total || 0
            this.adminCount = resData.adminCount || 0
          } else {
            if (resData.msg && resData.msg.includes('权限不足')) {
              this.$showError('权限不足', resData.msg || '只有管理员可以查看用户列表')
              setTimeout(() => {
                this.$router.push({ path: "/home" })
              }, 2000)
            } else {
              this.tableData = []
              this.total = 0
              if (resData.msg) {
                this.$showError('失败', resData.msg)
              }
            }
          }
        })
        .catch(err => {
          console.error('获取用户列表失败:', err)
          if (err.response && err.response.status === 403) {
            this.$showError('权限不足', '只有管理员可以查看用户列表')
            setTimeout(() => {
              this.$router.push({ path: "/home" })
            }, 2000)
          } else if (err.response && err.response.status === 401) {
            this.$showError('未登录', '请先登录')
            setTimeout(() => {
              this.$router.push({ path: "/login" })
            }, 1500)
          } else {
            this.$showError('失败', '获取用户列表失败，请重试')
          }
          this.tableData = []
          this.total = 0
        })
    },
    async handleMute(index, row) {
      const isLoggedIn = await requireLogin()
      if (!isLoggedIn) {
        const result = await this.$showLoginPrompt()
        if (result.isConfirmed) {
          this.$router.push({ path: "/login" })
        }
        return
      }

      // 检查是否为管理员
      if (row.role == '1') {
        this.$showError('错误', '管理员不可禁言')
        return
      }

      // 使用SweetAlert2创建自定义对话框
      const Swal = require('sweetalert2').default
      const { value: formValues } = await Swal.fire({
        title: '禁言用户',
        html: `
          <div style="text-align: left; padding: 20px;">
            <div style="margin-bottom: 20px;">
              <label style="display: block; margin-bottom: 8px; font-weight: bold;">禁言时长</label>
              <div style="display: flex; gap: 10px; align-items: center;">
                <input id="mute-number" type="number" min="1" value="1" 
                  style="flex: 1; padding: 8px; border: 1px solid #dcdfe6; border-radius: 4px; font-size: 14px;" />
                <select id="mute-unit" 
                  style="flex: 1; padding: 8px; border: 1px solid #dcdfe6; border-radius: 4px; font-size: 14px;">
                  <option value="小时">小时</option>
                  <option value="天">天</option>
                  <option value="周">周</option>
                  <option value="月">月</option>
                </select>
              </div>
            </div>
          </div>
        `,
        showCancelButton: true,
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        confirmButtonColor: '#409EFF',
        cancelButtonColor: '#909399',
        didOpen: () => {
          // 聚焦到输入框
          document.getElementById('mute-number').focus()
        },
        preConfirm: () => {
          const number = document.getElementById('mute-number').value
          const unit = document.getElementById('mute-unit').value
          if (!number || number < 1) {
            Swal.showValidationMessage('请输入有效的数字')
            return false
          }
          return { number, unit }
        }
      })

      if (formValues) {
        const { number, unit } = formValues
        const muteTime = `${number}${unit}`
        // 调用后端API实现禁言功能
        let token = localStorage.getItem("AUTO_TOKEN")
        await muteUser({ token, id: row.id, muteTime })
          .then(resData => {
            if (resData.code == 200) {
              this.$showSuccess('成功', `${row.account}账号成功禁言${muteTime}`)
              this.itemsUserFn()
            } else {
              this.$showError('失败', resData.msg || '禁言失败')
            }
          })
          .catch(() => {
            this.$showError('失败', '禁言失败，请重试')
          })
      }
    },
    async handleBan(index, row) {
      const isLoggedIn = await requireLogin()
      if (!isLoggedIn) {
        const result = await this.$showLoginPrompt()
        if (result.isConfirmed) {
          this.$router.push({ path: "/login" })
        }
        return
      }

      // 检查是否为管理员
      if (row.role == '1') {
        this.$showError('错误', '管理员不可封禁')
        return
      }

      // 使用SweetAlert2创建自定义对话框
      const Swal = require('sweetalert2').default
      const { value: formValues } = await Swal.fire({
        title: '封禁用户',
        html: `
          <div style="text-align: left; padding: 20px;">
            <div style="margin-bottom: 20px;">
              <label style="display: block; margin-bottom: 8px; font-weight: bold;">封禁时长</label>
              <div style="display: flex; gap: 10px; align-items: center;">
                <input id="ban-number" type="number" min="1" value="1" 
                  style="flex: 1; padding: 8px; border: 1px solid #dcdfe6; border-radius: 4px; font-size: 14px;" />
                <select id="ban-unit" 
                  style="flex: 1; padding: 8px; border: 1px solid #dcdfe6; border-radius: 4px; font-size: 14px;">
                  <option value="天">天</option>
                  <option value="周">周</option>
                  <option value="月">月</option>
                  <option value="年">年</option>
                  <option value="永封">永封</option>
                </select>
              </div>
            </div>
          </div>
        `,
        showCancelButton: true,
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        confirmButtonColor: '#409EFF',
        cancelButtonColor: '#909399',
        didOpen: () => {
          // 聚焦到输入框
          document.getElementById('ban-number').focus()
        },
        preConfirm: () => {
          const number = document.getElementById('ban-number').value
          const unit = document.getElementById('ban-unit').value
          if (unit === '永封') {
            return { number: 0, unit: '永封' }
          }
          if (!number || number < 1) {
            Swal.showValidationMessage('请输入有效的数字')
            return false
          }
          return { number, unit }
        }
      })

      if (formValues) {
        // 调用后端API封禁用户（封禁操作直接将role设置为-1，不需要时间参数）
        let token = localStorage.getItem("AUTO_TOKEN")
        await banUser({ token, id: row.id })
          .then(resData => {
            if (resData.code == 200) {
              this.$showSuccess('成功', '封禁成功')
              this.itemsUserFn()
            } else {
              this.$showError('失败', resData.msg || '封禁失败')
            }
          })
          .catch(() => {
            this.$showError('失败', '封禁失败，请重试')
          })
      }
    },
    async handleUnmute(index, row) {
      const isLoggedIn = await requireLogin()
      if (!isLoggedIn) {
        const result = await this.$showLoginPrompt()
        if (result.isConfirmed) {
          this.$router.push({ path: "/login" })
        }
        return
      }

      const result = await this.$showConfirm('提示', '是否解禁该账号？', '确认', '取消')
      if (result.isConfirmed) {
        let token = localStorage.getItem("AUTO_TOKEN")
        await unmuteUser({ token, id: row.id })
          .then(resData => {
            if (resData.code == 200) {
              this.$showSuccess('成功', '解禁成功')
              this.itemsUserFn()
            } else {
              this.$showError('失败', resData.msg || '解禁失败')
            }
          })
          .catch(() => {
            this.$showError('失败', '解禁失败，请重试')
          })
      }
    },
    async handleUnban(index, row) {
      const isLoggedIn = await requireLogin()
      if (!isLoggedIn) {
        const result = await this.$showLoginPrompt()
        if (result.isConfirmed) {
          this.$router.push({ path: "/login" })
        }
        return
      }

      const result = await this.$showConfirm('提示', '是否解封该账号？', '确认', '取消')
      if (result.isConfirmed) {
        let token = localStorage.getItem("AUTO_TOKEN")
        await unbanUser({ token, id: row.id })
          .then(resData => {
            if (resData.code == 200) {
              this.$showSuccess('成功', '解封成功')
              this.itemsUserFn()
            } else {
              this.$showError('失败', resData.msg || '解封失败')
            }
          })
          .catch(() => {
            this.$showError('失败', '解封失败，请重试')
          })
      }
    },
    async handleDelete(index, row) {
      const isLoggedIn = await requireLogin()
      if (!isLoggedIn) {
        const result = await this.$showLoginPrompt()
        if (result.isConfirmed) {
          this.$router.push({ path: "/login" })
        }
        return
      }

      // 如果是管理员，使用特殊提示文本
      const confirmText = row.role == '1'
        ? '您将要删除的是管理员账号，您确定要删除吗？'
        : '您确定要删除该用户吗？'

      const result = await this.$showConfirm('提示', confirmText, '确定', '取消')
      if (result.isConfirmed) {
        this.deleteUserFn(row.id)
      }
    },
    handleSearch() {
      this.page_num = 1
      this.itemsUserFn()
    },
    currentChangeFn(index) {
      this.page_num = index
      this.itemsUserFn()
    }
  },
  created() {
    this.itemsUserFn()
    this.$store.commit("addTab", this.$route)
  },
  watch: {
    $route: {
      immediate: true,
      deep: true,
      handler(newRoute) {
        this.$store.commit("addTab", newRoute)
      }
    }
  },
  async beforeRouteEnter(to, from, next) {
    // 检查登录状态
    const { checkLoginStatus } = require('../utils/auth')
    const isLoggedIn = await checkLoginStatus()

    if (!isLoggedIn) {
      const Swal = require('sweetalert2').default
      const result = await Swal.fire({
        icon: 'warning',
        title: '未登录',
        text: '您还没有登录，请先登录后再访问用户列表',
        showCancelButton: true,
        confirmButtonText: '去登录',
        cancelButtonText: '取消',
        confirmButtonColor: '#409EFF',
        cancelButtonColor: '#909399'
      })
      if (result.isConfirmed) {
        next({ path: "/login" })
      } else {
        next({ path: "/home" })
      }
      return
    }

    // 检查是否为管理员（通过localStorage中的角色判断）
    const role = localStorage.getItem("USER_ROLE")
    if (role !== '1') {
      const Swal = require('sweetalert2').default
      await Swal.fire({
        icon: 'error',
        title: '权限不足',
        text: '只有管理员可以查看用户列表',
        confirmButtonText: '确定',
        confirmButtonColor: '#409EFF'
      })
      next({ path: "/home" })
      return
    }

    // 是管理员，允许访问
    next()
  }
}
</script>

<style lang="less">
.article-list {
  .article-list-title {
    padding: 20px 0px;
    color: #303133;
  }

  .article-list-footer {
    margin-top: 15px;
    text-align: right;
  }

  .date-time {
    line-height: 1.5;
    white-space: pre-line;
  }
}
</style>
